package com.lcy.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainChat extends Activity implements OnClickListener {
 /** Called when the activity is first created. */
	
	private TextView tv;		
	private String m_SendMsg = null;
	private String userId = MessageBean.userId;	
	private Socket socket;	
	private String str = null;
	private InputStream in;
	private OutputStream out;
	
	private final Handler handler = new Handler();	
	private final static String IP = "150.11.10.87";
	private final static int PORT = 9001;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        try {
        	
			socket = new Socket( IP, PORT );	
			
		    tv = (TextView)findViewById(R.id.moniter);	
		    Button button = (Button)findViewById(R.id.sendbtn);		
			button.setOnClickListener(this);
			
			 Thread cThread = new Thread(){public void run(){
		         try{
		        	receiver();
		         } catch(Exception e){} }
		     };
		     cThread.start();		
			
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
    }
    
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub		
		
		EditText et = (EditText)findViewById(R.id.textinput);		
		m_SendMsg = et.getText().toString();
	    PrintWriter pw = new PrintWriter( new OutputStreamWriter( out ) );
		pw.println(m_SendMsg);
		pw.flush() ;
			
	}
	
	public void receiver(){
		
		try {
			
			 BufferedReader reader = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
			 
			 if(socket != null) {
				 
				 in = socket.getInputStream();
			     out = socket.getOutputStream();
			     PrintWriter pw = new PrintWriter( new OutputStreamWriter( out ) );
			     pw.println(userId);
			     pw.flush() ;
			       
				 while(socket != null && socket.isConnected()){
					str = reader.readLine();
					if( str == null ){
						break;
					}	
					
					handler.post(new Runnable(){
				         public void run() {
				          tv.setText( tv.getText()+str+"\n" );
				         }
				    });
				}
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
}
